const api = require('../../utils/api');
const reminderApi = api.reminder;
const app = getApp();

Page({
  data: {
    id: null,
    isEdit: false,
    loading: true,
    error: null,
    reminderMode: 'new',
    reminderId: null,
    reminder: {
      title: '',
      type: 'medicine',
      hour: 8,
      minute: 0,
      repeatDays: [1, 2, 3, 4, 5],
      enabled: true,
      priority: 'medium',
      note: ''
    },
    repeatTypeIndex: 1, // 默认工作日
    repeatTypeText: '工作日',
    types: [
      { label: '服药提醒', value: 'medicine' },
      { label: '血糖检测', value: 'glucose' },
      { label: '运动锻炼', value: 'exercise' },
      { label: '饮食控制', value: 'diet' },
      { label: '预约复诊', value: 'appointment' },
      { label: '其他提醒', value: 'other' }
    ],
    priorities: [
      { label: '高优先级', value: 'high' },
      { label: '中优先级', value: 'medium' },
      { label: '低优先级', value: 'low' }
    ],
    weekdays: [
      { value: 0, label: '周日' },
      { value: 1, label: '周一' },
      { value: 2, label: '周二' },
      { value: 3, label: '周三' },
      { value: 4, label: '周四' },
      { value: 5, label: '周五' },
      { value: 6, label: '周六' }
    ],
    timePickerVisible: false,
    submitDisabled: false,
    typeIndex: 0,
    currentTypeLabel: '服药提醒',
    timeString: '08:00',
    priorityIndex: 1,
    currentPriorityLabel: '中优先级',
    isMonday: true,
    isTuesday: true,
    isWednesday: true,
    isThursday: true,
    isFriday: true,
    isSaturday: false,
    isSunday: false
  },

  onLoad(options) {
    console.log('reminderEdit onLoad, options:', options);
    
    if (options.id) {
      this.setData({ 
        id: options.id,
        isEdit: true,
        loading: true  // 只有编辑模式才需要加载
      });
      this.fetchReminderData();
      wx.setNavigationBarTitle({
        title: '编辑提醒'
      });
    } else {
      // 新建模式，不需要加载数据
      this.setData({
        isEdit: false,
        loading: false
      });
      wx.setNavigationBarTitle({
        title: '新建提醒'
      });
      this.updateComputedProperties();
    }
  },

  updateComputedProperties() {
    this.updateTypeProperties();
    this.updateTimeString();
    this.updatePriorityProperties();
    this.updateWeekdayProperties();
    this.updateRepeatTypeProperties();
  },

  updateTypeProperties() {
    const typeIndex = this.data.types.findIndex(t => t.value === this.data.reminder.type);
    const currentTypeLabel = typeIndex >= 0 ? this.data.types[typeIndex].label : '未设置';
    this.setData({
      typeIndex,
      currentTypeLabel
    });
  },

  updateTimeString() {
    const { hour, minute } = this.data.reminder;
    const timeString = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
    this.setData({ timeString });
  },

  updatePriorityProperties() {
    const priorityIndex = this.data.priorities.findIndex(p => p.value === this.data.reminder.priority);
    const currentPriorityLabel = priorityIndex >= 0 ? this.data.priorities[priorityIndex].label : '未设置';
    this.setData({
      priorityIndex,
      currentPriorityLabel
    });
  },

  updateWeekdayProperties() {
    const repeatDays = this.data.reminder.repeatDays || [];
    this.setData({
      isMonday: repeatDays.includes(1),
      isTuesday: repeatDays.includes(2),
      isWednesday: repeatDays.includes(3),
      isThursday: repeatDays.includes(4),
      isFriday: repeatDays.includes(5),
      isSaturday: repeatDays.includes(6),
      isSunday: repeatDays.includes(0)
    });
  },

  updateRepeatTypeProperties() {
    const { repeatDays } = this.data.reminder;
    let repeatTypeIndex = 3; // 默认为自定义
    let repeatTypeText = '自定义';
    
    if (repeatDays.length === 7) {
      repeatTypeIndex = 0;
      repeatTypeText = '每日';
    } else if (repeatDays.length === 5 && 
               repeatDays.includes(1) && repeatDays.includes(2) && 
               repeatDays.includes(3) && repeatDays.includes(4) && 
               repeatDays.includes(5)) {
      repeatTypeIndex = 1;
      repeatTypeText = '工作日';
    } else if (repeatDays.length === 2 && 
              repeatDays.includes(0) && repeatDays.includes(6)) {
      repeatTypeIndex = 2;
      repeatTypeText = '周末';
    }
    
    this.setData({
      repeatTypeIndex,
      repeatTypeText
    });
  },

  async fetchReminderData() {
    this.setData({ loading: true });
    
    try {
      const result = await reminderApi.getReminderById(this.data.id);
      
      if (result && result.success && result.data) {
        // 转换优先级数字为字符串值
        let reminder = result.data;
        const priorityMap = {
          3: 'high',
          2: 'medium',
          1: 'low'
        };
        reminder.priority = priorityMap[reminder.priority] || 'medium';
        
        this.setData({
          reminder,
          loading: false,
          error: null
        });
        
        this.updateComputedProperties();
      } else {
        throw new Error('获取提醒详情失败');
      }
    } catch (error) {
      console.error('获取提醒详情失败', error);
      this.setData({
        loading: false,
        error: '获取提醒详情失败，请稍后重试'
      });
    }
  },

  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`reminder.${field}`]: value
    });
  },

  handleTypeChange(e) {
    const typeIndex = e.detail.value;
    const type = this.data.types[typeIndex].value;
    const currentTypeLabel = this.data.types[typeIndex].label;
    
    this.setData({
      'reminder.type': type,
      typeIndex,
      currentTypeLabel
    });
  },

  handlePriorityChange(e) {
    const priorityIndex = e.detail.value;
    const priority = this.data.priorities[priorityIndex].value;
    const currentPriorityLabel = this.data.priorities[priorityIndex].label;
    
    this.setData({
      'reminder.priority': priority,
      priorityIndex,
      currentPriorityLabel
    });
  },

  toggleTimePickerVisible() {
    this.setData({
      timePickerVisible: !this.data.timePickerVisible
    });
  },

  handleTimeChange(e) {
    const timeString = e.detail.value;
    const [hourStr, minuteStr] = timeString.split(':');
    const hour = parseInt(hourStr);
    const minute = parseInt(minuteStr);
    
    this.setData({
      'reminder.hour': hour,
      'reminder.minute': minute,
      timeString
    });
  },

  toggleDay(e) {
    const day = parseInt(e.currentTarget.dataset.day);
    const repeatDays = [...this.data.reminder.repeatDays];
    
    const index = repeatDays.indexOf(day);
    if (index >= 0) {
      repeatDays.splice(index, 1);
    } else {
      repeatDays.push(day);
    }
    
    this.setData({
      'reminder.repeatDays': repeatDays
    });
    
    this.updateWeekdayProperties();
    this.updateRepeatTypeProperties();
  },

  handleSelectAllWeekdays() {
    this.setData({
      'reminder.repeatDays': [0, 1, 2, 3, 4, 5, 6]
    });
    
    this.updateWeekdayProperties();
    this.updateRepeatTypeProperties();
  },

  handleSelectWeekdaysOnly() {
    this.setData({
      'reminder.repeatDays': [1, 2, 3, 4, 5]
    });
    
    this.updateWeekdayProperties();
    this.updateRepeatTypeProperties();
  },

  handleSelectWeekendsOnly() {
    this.setData({
      'reminder.repeatDays': [0, 6]
    });
    
    this.updateWeekdayProperties();
    this.updateRepeatTypeProperties();
  },

  handleClearWeekdays() {
    this.setData({
      'reminder.repeatDays': []
    });
    
    this.updateWeekdayProperties();
    this.updateRepeatTypeProperties();
  },

  toggleEnabled() {
    this.setData({
      'reminder.enabled': !this.data.reminder.enabled
    });
  },

  validateForm() {
    const { title, hour, minute } = this.data.reminder;
    
    if (!title.trim()) {
      wx.showToast({
        title: '请输入提醒标题',
        icon: 'none'
      });
      return false;
    }
    
    if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
      wx.showToast({
        title: '请设置有效的提醒时间',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  },

  handleSubmit(e) {
    const formValues = e.detail.value;
    const { reminder } = this.data;
    
    // 更新表单值
    reminder.title = formValues.title;
    reminder.note = formValues.note;
    reminder.enabled = formValues.enabled;
    
    // 验证表单
    if (!reminder.title) {
      wx.showToast({
        title: '请输入提醒标题',
        icon: 'none'
      });
      return;
    }
    
    if (reminder.repeatDays.length === 0) {
      wx.showToast({
        title: '请至少选择一天重复',
        icon: 'none'
      });
      return;
    }
    
    // 保存提醒
    this.saveReminder();
  },

  saveReminder() {
    const { reminder, isEdit, id } = this.data;
    
    // 显示加载状态
    wx.showLoading({
      title: isEdit ? '更新中...' : '创建中...'
    });
    
    console.log('保存提醒前数据:', JSON.stringify(reminder));
    
    // 创建API请求的数据副本，避免修改原始数据
    const reminderData = JSON.parse(JSON.stringify(reminder));
    
    // 确保重复日期是按顺序的
    reminderData.repeatDays = reminderData.repeatDays.sort((a, b) => a - b);
    
    // 转换优先级值为数字
    const priorityMap = {
      'high': 3,
      'medium': 2, 
      'low': 1
    };
    reminderData.priority = priorityMap[reminderData.priority] || 2;
    
    // 确保类型字段与后端匹配
    const typeMap = {
      'medicine': 'medication',
      'glucose': 'measurement',
      'exercise': 'exercise',
      'diet': 'medication',      // 将'diet'映射为'medication'，因为后端不支持'diet'
      'appointment': 'assessment',
      'other': 'medication'      // 将'other'映射为'medication'，因为后端不支持'other'或'general'
    };
    
    reminderData.type = typeMap[reminderData.type] || 'medication';  // 默认为'medication'
    
    console.log('转换后的提醒数据:', JSON.stringify(reminderData));
    
    // 根据模式选择创建或更新API
    const apiPromise = isEdit 
      ? reminderApi.updateReminder(id, reminderData)
      : reminderApi.createReminder(reminderData);
    
    apiPromise.then(res => {
      console.log('API响应:', JSON.stringify(res));
      wx.hideLoading();
      if (res && res.success) {
        wx.showToast({
          title: isEdit ? '更新成功' : '创建成功',
          icon: 'success'
        });
        
        // 延迟导航，确保提示显示
        setTimeout(() => {
          // 首先检查页面栈中是否有页面可以返回
          const pages = getCurrentPages();
          if (pages.length > 1) {
            // 有历史页面，可以安全地返回
            wx.navigateBack();
          } else {
            // 没有历史页面，重定向到健康提醒页面
            wx.redirectTo({
              url: '/pages/healthReminder/healthReminder'
            });
          }
        }, 1500);
      } else {
        wx.showToast({
          title: (res && res.message) || '操作失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('Save reminder error:', err);
      wx.hideLoading();
      wx.showToast({
        title: isEdit ? '更新失败' : '创建失败',
        icon: 'none'
      });
    });
  },

  handleCancel() {
    // 首先检查页面栈中是否有页面可以返回
    const pages = getCurrentPages();
    if (pages.length > 1) {
      // 有历史页面，可以安全地返回
      wx.navigateBack();
    } else {
      // 没有历史页面，重定向到健康提醒页面
      wx.redirectTo({
        url: '/pages/healthReminder/healthReminder'
      });
    }
  },

  handleRepeatTypeChange(e) {
    const index = parseInt(e.detail.value);
    let repeatDays = [];
    let repeatTypeText = '';
    
    switch (index) {
      case 0: // 每日
        repeatDays = [0, 1, 2, 3, 4, 5, 6];
        repeatTypeText = '每日';
        break;
      case 1: // 工作日
        repeatDays = [1, 2, 3, 4, 5];
        repeatTypeText = '工作日';
        break;
      case 2: // 周末
        repeatDays = [0, 6];
        repeatTypeText = '周末';
        break;
      case 3: // 自定义 - 保持现有设置
        // 如果之前没有任何设置，默认设为工作日
        if (this.data.reminder.repeatDays.length === 0) {
          repeatDays = [1, 2, 3, 4, 5];
          repeatTypeText = '自定义';
        } else {
          repeatDays = this.data.reminder.repeatDays;
          repeatTypeText = '自定义';
        }
        break;
    }
    
    this.setData({
      'reminder.repeatDays': repeatDays,
      repeatTypeIndex: index,
      repeatTypeText: repeatTypeText
    });
    
    this.updateWeekdayProperties();
  },
}); 